﻿using CoachingOrganizer.Logic.Common;
using CoachingOrganizer.Logic.Models.Tools.MoodLevel;
using CoachingOrganizer.Toolkit.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CoachingOrganizer.Logic.Logic.Tools.MoodLevel
{
    internal class MoodDayCacheLogic
    {
        private readonly MoodDayCacheModel _model;
        private readonly LogicExtender _logicExtender;
        private readonly MoodLevelLogic _upperLogic;
        private readonly MoodValueCacheLogic[] _values;

        public MoodDayCacheModel Model
        {
            get { return _model; }
        }

        public MoodValueCacheLogic[] Values
        {
            get { return _values; }
        }

        public MoodDayCacheLogic(LogicExtender logicExtender, MoodLevelLogic upperLogic, DateTime date)
            : this(new MoodDayCacheModel(date), logicExtender, upperLogic)
        {

        }

        public MoodDayCacheLogic(MoodDayCacheModel model, LogicExtender logicExtender, MoodLevelLogic upperLogic)
        {
            _model = model;
            _logicExtender = logicExtender;
            _upperLogic = upperLogic;
            int valuesCount = (int)(1.0 / _upperLogic.Model.Period.TotalDays);
            _values = new MoodValueCacheLogic[valuesCount];
            for (int i = 0; i < valuesCount; i++)
                _values[i] = new MoodValueCacheLogic(_logicExtender, this, _upperLogic, _upperLogic.Model.StartDate + TimeSpan.FromMinutes(_upperLogic.Model.Period.TotalMinutes * i));
            model.Values = _values.Select(l => l.Model).ToArray();
            model.SaveDelegate = Save;
        }

        private async Task<ActionResult> Save()
        {
            ActionResult result = ActionResult.ValidResult;
            foreach (MoodValueModel value in _upperLogic.EnumerateDayValues(_model.Date).ToArray())
                if (!(result = await value.Save()).IsValid)
                    return result;
            return result;
        }
    }
}
